package com.leyou.sms.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.leyou.common.utils.JsonUtils;
import com.leyou.sms.config.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class SmsUtils {

    private final SmsProperties prop;

    private final IAcsClient client;

    public SmsUtils(SmsProperties prop, IAcsClient acsClient) {
        this.prop = prop;
        this.client = acsClient;
    }

    public void sendVerifyCode(String phone, String code) {
        String param = "{\"code\":\"" + code + "\"}";
        sendMessage(phone, prop.getSignName(), prop.getVerifyCodeTemplate(), param);
    }

    private void sendMessage(String phone, String signName, String templateCode, String param) {
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(prop.getDomain());
        request.setVersion(prop.getVersion());
        request.setAction(prop.getAction());
        request.putQueryParameter("RegionId", prop.getRegionID());
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", param);
        try {
            CommonResponse response = client.getCommonResponse(request);

            String json = response.getData();
            Map<String, String> data = JsonUtils.toMap(json, String.class, String.class);
            // 判断执行结果
            if (!"OK".equalsIgnoreCase(data.get("Code"))) {
                // 发送短信失败！
                log.error("发送短信失败，错误码：{}, 原因：{}", data.get("Code"), data.get("Message"));
                throw new RuntimeException("发送短信失败！");
            }
            // 发送成功
            log.debug("发送短信成功，手机号：{}", phone);
        } catch (ServerException e) {
            log.error("发送短信失败，服务端异常！", e);
        } catch (ClientException e) {
            log.error("发送短信失败，客户端异常！", e);
        }
    }
}
